import json
import re
import urllib.request
from datetime import datetime, timedelta

from lxml import etree

from app.services.weather.hourly_weather import HourlyWeather

def wind_level_to_speed(level):
    mapping = {
        0: 0.1,
        1: 0.9,
        2: 2.5,
        3: 4.4,
        4: 6.7,
        5: 9.3,
        6: 12.3,
        7: 15.5,
        8: 19.0,
        9: 22.6,
        10: 26.5,
        11: 30.5,
        12: 35.0,
    }
    return mapping.get(level, 0)

def get_weather_html(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
    }
    request = urllib.request.Request(url=url, headers=headers)
    response = urllib.request.urlopen(request)
    html = response.read().decode('utf-8', errors='ignore')
    return html

def parse_weather(html):
    tree = etree.HTML(html)
    scripts = tree.xpath('//div[@class = "todayRight"]/script/text()')
    script_text = scripts[0]

    match = re.search(r'var hour3data=(\[\[.*?\]\]);', script_text, re.DOTALL)
    if not match:
        print("未能匹配到 hour3data")
        return [], []

    data_str = match.group(1)
    hour3data = json.loads(data_str)

    # 展平两个时间段数据（hour3data 是二维数组）
    all_data = hour3data[0] + hour3data[1]

    # 获取当前时间的时间戳（整点小时）
    now = datetime.now()
    now_hour_str = now.strftime("%Y%m%d%H")  # e.g. "2025071514"

    today_weather = []
    tomorrow_weather = []

    # 处理未来 24 小时的数据
    for item in all_data:
        time_str = item["jf"]
        if time_str >= now_hour_str:
            wind_level = int(item["jd"])
            wind_speed = wind_level_to_speed(wind_level)
            weather = HourlyWeather(
                weather_code=item["ja"],
                temperature=int(item["jb"]),
                precipitation_type=int(item["jc"]),
                wind_level=wind_level,
                humidity=int(item["je"]),
                wind_speed=wind_speed,
                time_str=time_str
            )

            if len(today_weather) < 24:
                today_weather.append(weather)

            # 明日的数据（用于 tomorrow_weather）
            if time_str.startswith((now + timedelta(days=1)).strftime("%Y%m%d")):
                tomorrow_weather.append(weather)

    return today_weather, tomorrow_weather

def get_weather():
    url = 'https://www.weather.com.cn/weather1dn/101201401.shtml'
    html = get_weather_html(url)
    return parse_weather(html)

if __name__ == '__main__':
    get_weather()